'use strict';

const { Service } = require('egg');

class Userservice extends Service {
  async getUserInfoFromWechat(js_code) {
    // 去微信查询openid
    const appid = 'wx18d59bb0e699d5b4';
    const secret = '36572275f4a9b36fee46def59054a78b';
    const res = await this.ctx.curl(
      `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`
    );
    return JSON.parse(res.data);
  }
  // 把用户信息存到数据库
  async saveUserInfo(userInfo) {
    const user = await this.app.mysql.get('wechatuser', { openid: userInfo.openid });
    if (!user) {
      // 如果没有用户信息，就创建一个用户信息
      const result = await this.app.mysql.insert('wechatuser', {
        openid: userInfo.openid,
        session_key: userInfo.session_key,
      });
      // 判断插入成功
      const insertSuccess = result.affectedRows === 1;
      console.log(insertSuccess, '用户插入成功');
    }
  }
}

module.exports = Userservice;
